import parser.JavaParser;
import parser.ParseException;
import symbol.SymbolTable;
import syntaxtree.CompilationUnit;
import syntaxtree.Tabulation;
import translationTable.XMLFileStream;
/**TODO typechecking/cohersion
 *
 * @author Benoit Petit <benoit.petit.info at gmail.com>
 */
public class Madkit2JanusTranslator {
    
   
    
    public static void main(String[] args){
        
        
//        XMLFileStream stream = new XMLFileStream("TranslationTable.xml");
        
        System.out.println("Madkit2Janus translator is running...");
        JavaParser parser;
        if(args.length==0){
                parser = new JavaParser(System.in);
        }
        else {
                java.io.File f = new java.io.File(args[0]);
                try {
                        parser = new JavaParser(new java.io.FileInputStream(f));
                }
                catch(java.io.FileNotFoundException e){
                        System.out.println("File not found. Here's the trace:\n"+e.getMessage());
                        return ;
                }
        }
        
        // Parse
        CompilationUnit unit = null;
        try {
            unit = parser.CompilationUnit();
        }
        catch(ParseException e) {
            e.printStackTrace();
        }
                
        if (unit==null) {
            System.out.println("Sorry, M2J was unable to traduce the file. It "
                    + "seems that an error occured in the parsing process."
                    + " parser.CompilationUnit() returned null.");
        }

        String translation = unit.translate();
        
        try
        {
            //if we used the translator on an existing file, we use the name of
            //this file preceded by M2J, else we give it the standard name
            //Translation
            java.io.File file = new java.io.File((args[0] == null) ? "Translation.java" : "M2J_"+args[0]);
            file.delete();
            file.createNewFile();
            java.io.FileWriter fw = new java.io.FileWriter(file,true);
            System.out.println("file: "+file.getAbsolutePath()+" translation: \n"+translation);
            java.io.PrintWriter writer = new java.io.PrintWriter(new java.io.BufferedWriter(fw));
            writer.print(translation);
            writer.close();
        }
        catch (java.io.FileNotFoundException e)
        {
            System.out.println("File not found. See the trace:\n");
            e.printStackTrace();
        } 
        catch (java.io.IOException e)
        {
            System.out.println("Sorry, M2J was unable to create the file. See the trace:\n");
            e.printStackTrace();
        }
        
        System.out.println("Symbol table:\n"+SymbolTable.getInstance().toString()+"\n\n");
        
        System.out.println("End of translation.");
    }
}
